#include <string.h>
#include <stdlib.h>  // TODO Required so far?
#include <ctype.h>
#include "string_tools.h"

int isalpha_uscore (int c)
{
  if (isalpha(c) || c == '_')
    return 1;

  return 0;
}

int isalnum_uscore (int c)
{
  if (isalnum(c) || c == '_')
    return 1;

  return 0;
}

int islower_uscore (int c)
{
  if (islower(c) || c == '_')
    return 1;

  return 0;
}

size_t chrn (char* s, char c)
{
  int i, n = 0;

  for (i = 0; i < strlen(s); i++)
    if (s[i] == c)
      n++;

  return n;
}

void wwipe (char* dest, char* src)
{
  int i, j = 0;
  unsigned short inqut = 0;

  for (i = 0; i < strlen(src); i++)
  {
    if (isgraph(src[i]) || (inqut%2) == 1)
    {
      dest[j] = src[i];
      j++;
    }
    if (src[i] == '"')
      inqut++;
  }

  return;
}

void strtocfn (char* dest, char* src, int(*tfn)(int))
{
  int i;

  for (i = 0; i < strlen(src); i++)
    dest[i] = (*tfn)(src[i]);

  return;
}

int strctestfn (char* test, int(*tfn)(int))
{
  int i, res = 1;

  for (i = 0; i < strlen(test); i++)
    if ((*tfn)(test[i]) == 0)
      res = 0;

  return res;
}

void strstrp (char* dest, char* src)
{
  int i, m = 0;
  unsigned short s = 0;

  for (i = 0; i < strlen(src); i++)
  {
    switch (s)
    {
      case 0:
        if (isgraph(src[i]))
          s = 1;
      case 1:
        if (isgraph(src[i]))
        {
          dest[m] = src[i];
          m++;
        }
        if (isspace(src[i]) && isgraph(src[i-1]))
        {
          dest[m] = src[i];
          m++;
        }
      break;
    }
  }

  if (isspace(dest[strlen(dest) - 1]))
    dest[strlen(dest) - 1] = 0;
}

int xstrcmp(const void *a, const void *b) 
{ 
    const char **xa = (const char **)a;
    const char **xb = (const char **)b;

    return strcmp(*xa, *xb);
}